package com.duqc.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName FileChannelDemo
 * @Description 文件管道
 * @Author duqc
 * @Date 2021/8/23
 **/
public class FileChannelDemo {

    public static void main(String[] args) throws Exception {
        //获取文件输入流
        File file = new File("highgo.docx");
        FileInputStream inputStream = new FileInputStream(file);
        //从文件输入流获取通道
        FileChannel inputStreamChannel = inputStream.getChannel();
        //获取文件输出流
        FileOutputStream outputStream = new FileOutputStream("highgo1.docx");
        //从文件输出流获取通道
        FileChannel outputStreamChannel = outputStream.getChannel();
        //创建一个byteBuffer，小文件所以就直接一次读取，不分多次循环了
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
//        //把输入流通道的数据读取到缓冲区
//        inputStreamChannel.read(byteBuffer);
//        //切换成读模式
//        byteBuffer.flip();
//        //把数据从缓冲区写道输入流管道
//        outputStreamChannel.write(byteBuffer);
//
//        //transferTo()，将源通道的数据传输到目的通道中
//        inputStreamChannel.transferTo(0, byteBuffer.limit(), outputStreamChannel);

        //transferFrom()，将来自源通道的数据传输到目的通道中
        outputStreamChannel.transferFrom(outputStreamChannel, 0, byteBuffer.limit());

        //关闭通道
        outputStream.close();
        outputStreamChannel.close();
        inputStream.close();
        inputStreamChannel.close();
    }

}
